define(function(require, exports, module) {
	
	require("ztree");
	
	module.exports = function() {
		var zTree = {};
		var row = {};
		return {
			data: {
				title:$.i18n.prop("sys.role.manager.perm"),
				button: {
					submit:$.i18n.prop("sys.submit")
				}
			},
			methods: {
				init: function(data) {
					var me = this;
					row = data;
					this.initTree(function() {me.loading("close");});
					return false;
				},
				//初始化权限树
				initTree:function(complete) {
					var me = this;
					var ul = $(this.$el).find("ul");
					var setting = {
						data : {
							simpleData: {
								enable: true,
								pIdKey: "parent_id"
							}
						},
						async : {
							enable : true,
							url:"/api/role/tree",
							dataType:"json",
							otherParam:{
								id:row.id
							},
							dataFilter:function(treeId, parentNode, responseData) {
								var data = responseData.message;
								data.name = $.i18n.prop("sys.select", [$.i18n.prop(data.i18n)]);
								return [data];
							}
						},
						check : {
							enable : true,
							chkStyle : "checkbox",
						},
						callback : {
							onAsyncSuccess: function(event, treeId, treeNode, data) {
								var perms = data.message.perms;
								for(var i=0; i<perms.length; i++) {
									var node = zTree.getNodeByParam("id", perms[i], null);
									zTree.checkNode(node, true, false, false);
								} 
								
								if($.isFunction(complete)) {
									complete();
								}
							}
						}
					};
					zTree = $.fn.zTree.init(ul, setting);
				},
				submit : function() {
					var items = zTree.getCheckedNodes(true);
					var permIds = []; 
					$(items).each(function() {
						permIds.push(this.id);
					});
					$.post("/api/role/perm", {
						id:row.id,
						permIds:permIds
					}, function(data) {}, "json");
					this.closeWindow();
				},
				destroy: function() {
					zTree.destroy();
				}
			}
		}
	}
});